/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package communication;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import objects.AudioClip;
import objects.MP3Clip;
import sun.net.www.http.HttpClient;

/**
 *
 * @author Irzh
 */
public class HostCommunication {
    
    // singletone ----------------------------------------------------
    private HostCommunication(){}
    private static HostCommunication hs = new HostCommunication();
    
    public static HostCommunication get(){
        return hs;
    }
    // ---------------------------------------------------------------
    
    public List<AudioClip> getClips(){
        List<AudioClip> res = new ArrayList<AudioClip>();
        List<ClipRecord> cl;
        StringBuilder sb = new StringBuilder();
        try {
            URL oracle = new URL("http://sharecomposition.appspot.com/getClips");
        
            BufferedReader in = new BufferedReader(
            new InputStreamReader(oracle.openStream()));

            String inputLine;
            while ((inputLine = in.readLine()) != null)
                sb.append(inputLine);
            in.close();
        } catch (Exception e) {
        }
        
        String json = sb.toString();
        Gson gson = new Gson();
        
        Type collectionType = new TypeToken<Collection<ClipRecord>>() {}.getType();
        
        cl = gson.fromJson(json, collectionType);
        
        for(ClipRecord cr : cl){
            res.add(MP3Clip.createFromRecord(cr));
        }
        
        return res;
    }
}
